<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>await错误处理流程</title>
</head>
<body>
    <script>
        class ParamError extends Error{
            constructor(msg){
                super(msg);
                this.name = "paramError";
            }
        }

        class HttpError extends Error{
            constructor(msg){
                super(msg);
                this.name = "httpError";
            }
        }

        function ajax(url){
            return new Promise((resolve,reject) => {
                if(!/^http/.test(url)){
                    throw new ParamError("请求地址格式错误");
                }

                let xhr = new XMLHttpRequest();
                xhr.open("GET",url);
                xhr.send();
                xhr.onload = function(){
                    if(this.status == 200){
                        resolve(JSON.parse(this.response));
                    }else if(this.status == 404){
                        reject(new HttpError("请求参数错误"));
                    }else{
                        reject("加载失败");
                    }
                };
                xhr.onerror = function (){
                    reject(this);
                }
            })
        }


        // 方法一：外部处理
        // async function hd(type){
        //     let jiaDian = await ajax(`ahttp://localhost:8008/index.php/api/home/getJiaDianList?type=${type}`);
        //     return jiaDian;
        // }

        // hd(1).then(value => {
        //     console.log(value);
        // }).catch(
        //     error => alert(error.message)
        // )

        // 方法二：内部try...catch... 处理
        async function hd(type){
            try {
                let jiaDian = await ajax(`ahttp://localhost:8008/index.php/api/home/getJiaDianList?type=${type}`);
                return jiaDian;
            } catch (error) {
                alert(error.message)
            }
        } 

        hd(1).then(value => {
            console.log(value);
        })
    </script>
</body>
</html>